package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.dao.*;
import cc.rengu.igas.bomp.common.dao.impl.*;
import cc.rengu.igas.bomp.common.entity.*;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.InspectTaskDetailBean;
import cc.rengu.igas.bomp.facade.request.MchntInspectListQueryRequest;
import cc.rengu.igas.bomp.facade.response.MchntInspectListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/01
 */
public class MchntInspectListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntInspectListQueryRequest mchntInspectListQueryRequest = new MchntInspectListQueryRequest();
        ConvertUtil.convertOutput(mchntInspectListQueryRequest);
        return mchntInspectListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        MchntInspectListQueryRequest mchntInspectListQueryRequest = (MchntInspectListQueryRequest) request;
        MchntInspectListQueryResponse mchntInspectListQueryResponse = new MchntInspectListQueryResponse();
        /*获取法人行号*/
        String instId = mchntInspectListQueryRequest.getHeader().getInstId();
        /*获取用户标识*/
        String userId = mchntInspectListQueryRequest.getUserId();
        /*获取商户号*/
        String mchntNo = mchntInspectListQueryRequest.getMchntNo();
        /*获取商户名*/
        String mchntName = mchntInspectListQueryRequest.getMchntName();
        /*获取商户类型*/
        String mchntType = mchntInspectListQueryRequest.getMchntType();
        /*获取收单机构*/
        String signInstId = mchntInspectListQueryRequest.getSignInstId();
        /*获取巡检机构*/
        String inspectInstId = mchntInspectListQueryRequest.getInspectInstId();
        /*获取巡检方式*/
        String inspectType = mchntInspectListQueryRequest.getInspectType();
        /*获取开始日期*/
        String startDate = mchntInspectListQueryRequest.getStartDate();
        /*获取截止日期*/
        String endDate = mchntInspectListQueryRequest.getEndDate();
        /*巡检状态*/
        String inspectStatus = mchntInspectListQueryRequest.getInspectStatus();
        /*必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId)) {
            rglog.error("必填性校验失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        int pageIndex = mchntInspectListQueryRequest.getPageIndex();
        int pageSize = mchntInspectListQueryRequest.getPageSize();
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(pageSize);
        /*根据用户标识查询用户所属机构*/
        AuthUserMapper authUserMapper = new AuthUserMapperImpl();
        AuthUser authUser = authUserMapper.selectAuthUserById(userId);
        if (null == authUser) {
            rglog.error("查询用户信息失败");
            throw new BizException(RespCodeEnum.QUERY_AUTH_USER_IS_NULL.getRespCode(), RespCodeEnum.QUERY_AUTH_USER_IS_NULL.getRespDesc());
        }
        /*查询商户巡检信息列表*/
        InspectTaskDetailMapper inspectTaskDetailMapper = new InspectTaskDetailMapperImpl();
        InspectTaskDetail inspectTaskDetail = new InspectTaskDetail();
        /*法人行号赋值*/
        inspectTaskDetail.setInstId(instId);
        /*商户号模糊查询条件赋值*/
        if (!StringUtil.isEmptyOrNull(mchntNo)) {
            inspectTaskDetail.setMchntNo("%" + mchntNo + "%");
        }
        /*商户名模糊查询条件赋值*/
        if (!StringUtil.isEmptyOrNull(mchntName)) {
            inspectTaskDetail.setMchntName("%" + mchntName + "%");
        }
        /*商户类型赋值*/
        if (!StringUtil.isEmptyOrNull(mchntType)) {
            inspectTaskDetail.setMchntType(mchntType);
        }
        /*商户签约（收单）机构赋值*/
        if (!StringUtil.isEmptyOrNull(signInstId)) {
            inspectTaskDetail.setSignInstId(signInstId);
        }
        /*商户巡检机构赋值*/
        if (!StringUtil.isEmptyOrNull(inspectInstId)) {
            inspectTaskDetail.setInspectInstId(inspectInstId);
        }
        /*商户巡检方式赋值*/
        if (!StringUtil.isEmptyOrNull(inspectType)) {
            inspectTaskDetail.setInspectType(inspectType);
        }
        /*开始日期赋值*/
        if (!StringUtil.isEmptyOrNull(startDate)) {
            inspectTaskDetail.setInspectBeginTime(startDate);
        }
        /*截止日期赋值*/
        if (!StringUtil.isEmptyOrNull(endDate)) {
            inspectTaskDetail.setInspectEndTime(endDate);
        }
        /*巡检状态赋值*/
        if (!StringUtil.isEmptyOrNull(inspectStatus)) {
            inspectTaskDetail.setInspectStatus(inspectStatus);
        }
        /*用户所属机构*/
        inspectTaskDetail.setRemark1(authUser.getOrgCode());
        PageResult pageResult = inspectTaskDetailMapper.selectBompInspectTaskDetailByQueryFilter(instId, inspectTaskDetail, pageInfo);
        if (null == pageResult) {
            rglog.error("商户巡检记录查询失败!");
            throw new BizException(RespCodeEnum.MCHNT_INSPECT_INFO_ERROR.getRespCode(), RespCodeEnum.MCHNT_INSPECT_INFO_ERROR.getRespDesc());
        }
        pageInfo = pageResult.getPageInfo();
        List<InspectTaskDetail> inspectTaskDetailList = pageResult.getResult().stream().map(item -> (InspectTaskDetail) item).collect(Collectors.toList());
        //     List<InspectTaskDetail> inspectTaskDetails = new ArrayList<>();
        List<InspectTaskDetailBean> inspectTaskDetailBeanList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(inspectTaskDetailList)) {

          /*  inspectTaskDetails = inspectTaskDetails.stream().sorted(Comparator.comparing(InspectTaskDetail::getInspectTime,Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
            Collections.reverse(inspectTaskDetails);*/
            /*  根据分页查询条件截取相关数据记录 */
            mchntInspectListQueryResponse.setPageIndex(pageInfo.getPageIndex());
            mchntInspectListQueryResponse.setPageSize(pageInfo.getPageSize());
            mchntInspectListQueryResponse.setTotalRows(pageInfo.getTotalRows());
            mchntInspectListQueryResponse.setTotalPage(pageInfo.getTotalPage());
            inspectTaskDetailList.forEach(item -> convMchntTaskDetailInfo(item, inspectTaskDetailBeanList));
            mchntInspectListQueryResponse.setInspectTaskDetailList(inspectTaskDetailBeanList);
        }
        /* 按照接口转换基础产品信息并响应给请求方 */
        BizResponse<MchntInspectListQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntInspectListQueryResponse);
        return bizResponse;
    }

    /**
     * inspectTaskDetail 任务详情信息
     * inspectTaskDetailBeanList 响应任务详情信息
     */
    private void convMchntTaskDetailInfo(InspectTaskDetail inspectTaskDetail, List<InspectTaskDetailBean> inspectTaskDetailBeanList) {
        InspectTaskDetailBean inspectTaskDetailBean = new InspectTaskDetailBean();
        BeanUtil.beanCopy(inspectTaskDetail, inspectTaskDetailBean);
        try {
            /*查询组织机构*/
            OrganizationMapper organizationMapper = new OrganizationMapperImpl();
            /*签约机构名称查询*/
            Organization signOrg = organizationMapper.selectOrganizationByPrimaryKey(inspectTaskDetail.getInstId(), inspectTaskDetail.getSignInstId());
            if (null != signOrg) {
                inspectTaskDetailBean.setSignInstName(signOrg.getOrgName());
            }
            /*巡检机构名称查询*/
            Organization inspectOrg = organizationMapper.selectOrganizationByPrimaryKey(inspectTaskDetail.getInstId(), inspectTaskDetail.getInspectInstId());
            if (null != inspectOrg) {
                inspectTaskDetailBean.setInspectInstName(inspectOrg.getOrgName());
            }
            /*查询商户等级*/
            BompMchntLevelInfoMapper bompMchntLevelInfoMapper = new BompMchntLevelInfoMapperImpl();
            BompMchntLevelInfo bompMchntLevelInfo = bompMchntLevelInfoMapper.selectBompMchntLevelInfoByMchntLevelCode(inspectTaskDetail.getInstId(), inspectTaskDetail.getMchntLevel());
            if (null != bompMchntLevelInfo) {
                inspectTaskDetailBean.setMchntLevelName(bompMchntLevelInfo.getMchntLevelName());
            }
            /*查询巡检任务名称*/
            InspectTaskInfoMapper nspectTaskInfoMapper = new InspectTaskInfoMapperImpl();
            InspectTaskInfo inspectTaskInfo = nspectTaskInfoMapper.selectInspectTaskInfoByPrimaryKey(inspectTaskDetail.getInstId(), inspectTaskDetail.getInspectTaskNo());
            if (null != inspectTaskInfo) {
                inspectTaskDetailBean.setInspectTaskDesc(inspectTaskInfo.getInspectTaskDesc());
            }
            inspectTaskDetailBeanList.add(inspectTaskDetailBean);
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("巡检任务详情查询列表信息转换失败:{}", byteArrayOutputStream.toString());
        }

    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntInspectListQueryResponse mchntInspectListQueryResponse = (MchntInspectListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntInspectListQueryResponse);
    }
}
